﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Windows.Documents;

namespace MoneyWentWhere.DataModel.Tx
{
    public class NormalTxSettings : TxSettings
    {
        const string NewPrefix = "new: '";
        const string NewSuffix = "'";

        public override TransactionKind Kind
        {
            get { return TransactionKind.Normal; }
        }

        public string Category;
        public NormalTxSettings(String category)
        {
            if (category == null) { category = ""; }

            if (category.StartsWith(NewPrefix) &&
                category.EndsWith(NewSuffix))
            {
                int len = category.Length - NewPrefix.Length - NewSuffix.Length;
                if (len >= 0)
                {
                    category = category.Substring(NewPrefix.Length, len);
                }
            }

            Category = category.Trim();
        }

        new public static NormalTxSettings Parse(String rep)
        {
            return new NormalTxSettings(rep);
        }
        public override string ToRepString()
        {
            return Category;
        }

        new internal static NormalTxSettings Create(Transaction t)
        {
            return new NormalTxSettings(t.Category);
        }

        protected override void ApplyCore(Transaction t)
        {
            t.Category = Category;
        }

        public void FillAutoComplete(IList list, out int selectedIndex,
            Transaction tx, List<String> categories, bool useFilter)
        {
            selectedIndex = -1;
            if (categories == null) { return; }

            String filter = "";
            if (useFilter) { filter = Category.ToUpper().Trim(); }
            
            for (int i = 0; i < categories.Count; i++)
            {
                String cat = categories[i];
                String ucCat = cat.ToUpper();

                if (!useFilter ||
                    ucCat.Contains(filter))
                {
                    list.Add(cat);
                }

                if (cat == Category)
                {
                    selectedIndex = list.Count - 1;
                }
            }

            // Select the best match (shortest for now).
            if (selectedIndex == -1)
            {
                int minLength;
                selectedIndex = IndexOfMinLengthItem(list, out minLength);

                // Add a new item
                if (minLength != filter.Length && 
                    !String.IsNullOrEmpty(Category))
                {
                    list.Add(NewPrefix + Category + NewSuffix);
                    if (selectedIndex == -1) { selectedIndex = 0; }
                }
            }
        }

    }
}
